import vtkRenderer from "@kitware/vtk.js/Rendering/Core/Renderer"
import vtkRenderWindow from "@kitware/vtk.js/Rendering/Core/RenderWindow"

import vtkFullScreenRenderWindow from "@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow"
import { Application } from "../App.ts"
import { AxisActor } from "../Core"
import vtkOpenGLRenderWindow from "@kitware/vtk.js/Rendering/OpenGL/RenderWindow"
import vtkRenderWindowInteractor from "@kitware/vtk.js/Rendering/Core/RenderWindowInteractor"
import vtkInteractorStyleTrackballCamera from "@kitware/vtk.js/Interaction/Style/InteractorStyleTrackballCamera"
import vtkCamera from "@kitware/vtk.js/Rendering/Core/Camera"
import { Vector3 } from "stl-typescript"
export class AxisSystem {
  parent: Application
  element = document.createElement("div")
  axis = new AxisActor()
  private renderer: vtkRenderer
  private window: vtkRenderWindow
  private instance: vtkOpenGLRenderWindow
  private camera: vtkCamera
  constructor(parent: Application) {
    this.parent = parent
    this.createDom()
  }

  createDom() {
    const div = this.element
    div.style.position = "absolute"
    div.style.width = "100px"
    div.style.height = "100px"
    div.style.bottom = "40px"
    div.style.left = "40px"
    div.style.background="transparent"
  }

  init() {
    const instance = vtkOpenGLRenderWindow.newInstance()
    this.instance = instance
    instance.setContainer(this.element)
    instance.setSize(this.element.clientWidth, this.element.clientHeight)
    this.renderer = vtkRenderer.newInstance()
    this.renderer.setBackground(0, 0, 0, 0)
    this.window = vtkRenderWindow.newInstance()
    const camera = this.renderer.getActiveCamera()
    this.camera = camera
    this.window.addView(this.instance)
    this.window.addRenderer(this.renderer)
    // 🍔💶
    const interactor = vtkRenderWindowInteractor.newInstance()
    interactor.setView(this.instance)
    interactor.initialize()
    interactor.setContainer(this.element)

    interactor.setInteractorStyle(
      vtkInteractorStyleTrackballCamera.newInstance()
    )
    this.axis.children.forEach((ac) => {
      this.renderer.addActor(ac)
    })
    // this.renderer.resetCamera()
    camera.setPosition(0, 0, 4)
    this.window.render()
  }

  update(camera: vtkCamera) {
    const cameraPosition = new Vector3(...camera.getPosition())
    const len = cameraPosition.length()
    const r = cameraPosition.multiplyScalar((1 / len) * 4)
    this.camera.setPosition(r.x, r.y, r.z)
    this.window.render()
  }

  mount() {
    this.parent.container.append(this.element)
    this.init()
  }
}
